package com.eight.cloud.admin.facade;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.eight.cloud.admin.service.*;
import com.eight.cloud.admin.entity.RoleEntity;
import com.eight.cloud.admin.entity.SysTenantEntity;
import com.eight.cloud.admin.entity.UserEntity;
import com.eight.cloud.admin.model.dto.RoleDto;
import com.eight.cloud.admin.model.dto.TenantSettledDto;
import com.eight.cloud.admin.model.dto.UserDto;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.eight.cloud.core.global.constant.DataScopeConstants.DATA_SCOPE_ALL;
import static com.eight.cloud.core.global.constant.NumConstant.ONE;

/**
 * 租户外观业务类
 *
 * @ClassName: SysTenantFacade
 * @Author: TXC
 * @Date: 2024-10-29 14:55
 **/
@Service
public class SysTenantFacade {
    @Resource
    private ISysTenantService tenantService;
    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;
    @Resource
    private IRolePermissionService rolePermissionService;
    @Resource
    private IPermissionService permissionService;

    @Transactional
    public boolean save(TenantSettledDto settledVo) {
        // 创建租户
        SysTenantEntity tenantEntity = new SysTenantEntity();
        tenantEntity.setName(settledVo.getName());
        tenantEntity.setType(settledVo.getType());
        tenantEntity.setStatus(ONE);
        tenantEntity = tenantService.add(tenantEntity);
        // 创建租户管理员账户
        UserDto userDto = new UserDto();
        BeanUtil.copyProperties(settledVo, userDto);
        userDto.setTenantId(tenantEntity.getUuid());
        UserEntity user = userService.register(userDto);
        // 创建管理员角色
        RoleDto roleDto = new RoleDto();
        roleDto.setCode(userDto.getUsername());
        roleDto.setName("管理员");
        roleDto.setTenantId(tenantEntity.getUuid());
        roleDto.setDataScope(DATA_SCOPE_ALL);
        RoleEntity role = roleService.createRole(roleDto);
        // 授权
        rolePermissionService.flush(role, permissionService.getPermissionCodes());
        return ObjectUtil.isNotNull(user);
    }
}
